<comment>
# 组件注释
切片下发页面
</comment>
<template>
  <div class="sliceIssued">
    <van-form validate-first label-width="100" @submit="onSubmit">
      <van-field name="radio" label="操作类型">
        <template #input>
          <van-radio-group v-model="formData.orderType" direction="horizontal">
            <van-radio name="CREATE">创建</van-radio>
            <van-radio name="CREATE" disabled>删除</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <div class="van-doc-demo-block__title">用户信息</div>

      <van-field
        v-model="formData.MDN"
        class="require-input"
        name="手机号"
        label="手机号"
        placeholder="仅支持填写数字"
        :rules="[{ required: true, pattern, message: '仅支持填写数字' }]"
      />

      <div class="van-doc-demo-block__title">切片参数</div>

      <van-field
        readonly
        clickable
        class="require-input"
        name="picker"
        :value="formData.usage"
        label="业务场景"
        placeholder="点击选择业务场景"
        :rules="[{ required: true}]"
        @click="showBusinPicker = true"
      />
      <van-popup v-model="showBusinPicker" position="bottom">
        <van-picker show-toolbar :columns="businColunms" @confirm="onConfirmBusin" @cancel="showBusinPicker = false" />
      </van-popup>

      <van-field
        v-model="formData.VDR"
        class="require-input"
        name="视频码率"
        label="视频码率(Kbps)"
        placeholder="仅支持填写数字"
        :rules="[{ required: true, pattern, message: '仅支持填写数字' }]"
      />

      <van-field
        v-model="formData.expDataRateUL"
        class="require-input"
        name="用户上行体验速率(Kbps)"
        label="用户上行体验速率(Kbps)"
        placeholder="仅支持填写数字"
        :rules="[{ required: true, pattern, message: '仅支持填写数字' }]"
      />

      <van-field
        v-model="formData.expDataRateDL"
        class="require-input"
        name="用户下行体验速率(Kbps)"
        label="用户下行体验速率(Kbps)"
        placeholder="仅支持填写数字"
        :rules="[{ required: true, pattern, message: '仅支持填写数字' }]"
      />

      <van-field
        v-model="formData.maxNumberofPDUSession"
        name="最大同时在线用户数"
        label="最大同时在线用户数"
        placeholder="仅支持填写数字"
        :rules="[{ pattern, message: '仅支持填写数字' }]"
      />

      <van-field
        readonly
        clickable
        name="picker"
        :value="dnnTypeSelected"
        label="DNN类型"
        placeholder="点击选择类型"
        @click="showDNNPicker = true"
      />
      <van-popup v-model="showDNNPicker" position="bottom">
        <van-picker show-toolbar :columns="DNNcolumns" @confirm="onConfirmDNNType" @cancel="showDNNPicker = false" />
      </van-popup>

      <van-field
        readonly
        clickable
        class="require-input"
        name="datetimePicker"
        :value="formData.stime"
        label="生效开始日期"
        placeholder="点击选择时间"
        :rules="[{ required: true, message: '请选择时间' }]"
        @click="showTimePicker = true"
      />
      <van-popup v-model="showTimePicker" position="bottom">
        <van-datetime-picker
          type="datetime"
          title="选择完整时间"
          :min-date="new Date()"
          :formatter="formatter"
          @confirm="onConfirmTime"
          @cancel="showTimePicker = false"
        />
      </van-popup>

      <van-field
        readonly
        clickable
        class="require-input"
        name="datetimePicker"
        :value="formData.etime"
        label="生效结束日期"
        placeholder="点击选择时间"
        :rules="[{ required: true, message: '请选择时间' }]"
        @click="showTimePickerEnd = true"
      />
      <van-popup v-model="showTimePickerEnd" position="bottom">
        <van-datetime-picker
          type="datetime"
          title="选择完整时间"
          :min-date="new Date()"
          :formatter="formatter"
          @confirm="onConfirmTimeEnd"
          @cancel="showTimePickerEnd = false"
        />
      </van-popup>

      <div style="margin: 16px">
        <van-row>
          <van-col span="10">
            <van-button round block type="info" native-type="submit" @click="btnType = 'submit'">提交</van-button>
          </van-col>
          <van-col span="4"></van-col>
          <van-col span="10">
            <van-button round block type="info" native-type="submit" @click="btnType = 'query'"
              >切片使用查询</van-button
            >
          </van-col>
        </van-row>
      </div>
    </van-form>
  </div>
</template>

<script>
import { formatter } from '@/utils/commonUtils.js'
import callApi from '@/MockApi'
import { Toast } from 'vant'
import {
  getSnssaiByMd,
  createBusinssByApp,
  choiceSnssai,
  deploy,
  insertSnssaiByMdn,
  getServTask,
  getServTaskLogDetail,
  getTnResCreateLog
} from '../../api/slice'
export default {
  name: 'SliceIssued',
  components: {},
  data() {
    return {
      wsnbr: '',
      showBusinPicker: false,
      infos: {},
      taskid: '',
      showDNNPicker: false,
      showTimePicker: false,
      showTimePickerEnd: false,
      formatter: formatter,
      btnType: '',
      failureReason: '',
      businColunms: ['专用切片+专用DNN', '5QI高优先级'],
      DNNcolumns: ['上行带宽保障类', '下行带宽保障类', '上下行带宽保障类'],
      dnnTypeSelected: '',
      formData: {
        usage: '',
        orderType: 'CREATE',
        MDN: '',
        VDR: '',
        expDataRateUL: '',
        expDataRateDL: '',
        maxNumberofPDUSession: '',
        dnnType: '',
        stime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        etime: this.$moment().add(1, 'years').format('YYYY-MM-DD HH:mm:ss')
      },
      // 校验数字，可为空
      pattern: /^$|^\d+(\.\d+)?$/,
      oneOrTwo: /^[1-2]{1}$/,
      dnnMap: {
        上行带宽保障类: '1',
        下行带宽保障类: '2',
        上下行带宽保障类: '3'
      },
      RNID: null,
      TNID: null,
      CNID: null,
      domainIsSuccess: {
        RN: false,
        CN: false,
        TN: true
      }
    }
  },
  props: {},
  watch: {},
  methods: {
    onSubmit() {
      this.formData.dnnType = this.dnnMap[this.dnnTypeSelected] ? this.dnnMap[this.dnnTypeSelected] : ''
      if (this.btnType === 'submit') {
        // 加载loading
        Toast.loading()
        // 点击提交按钮
        const param = {
          userData: {
            MDN: this.formData.MDN
          }
        }
        // 查询当前MDN号是否已经在下发中，若已经正在下发中，则跳转到切片创建页面，若已经完成或者不存在，则走下述流程
        // api/rest/worksheet/v1/5GSlice/getSnssaiByMdn
        getSnssaiByMd(param).then(res => {
          // 判断状态
          const { exist, mdnStatus } = res
          if (exist && exist == 1 && mdnStatus == 0) {
            Toast('弹框提示，该MDN号正在下发中，请等待')
          } else {
            this.createBusinssByApp()
          }
        })
      } else {
        // 点击查询按钮
        this.$router.push({
          path: '/slice/create',
          query: { MDN: this.formData.MDN }
        })
      }
    },
    //
    createBusinssByApp() {
      const params = {
        userData: {
          MDN: this.formData.MDN
        },
        snssaiData: {
          orderType: this.formData.orderType,
          VDR: this.formData.VDR,
          expDataRateDL: this.formData.expDataRateDL,
          expDataRateUL: this.formData.expDataRateUL,
          maxNumberofPDUSession: this.formData.maxNumberofPDUSession,
          usage: this.formData.usage === '专用切片+专用DNN' ? '1' : '2',
          dnnType: this.formData.dnnType,
          stime: this.formData.stime,
          etime: this.formData.etime
        }
      }

      // api/rest/worksheet/v1/5GSlice/createBusinssByApp
      createBusinssByApp({ ...params }).then(data => {
        const { wsnbr, status } = data
        this.infos = data
        this.wsnbr = wsnbr

        if (status == 0) {
          this.$router.push({
            path: '/slice/create',
            query: { MDN: this.formData.MDN }
          })
        } else {
          this.choiceSnssai()
        }
      })
    },
    // api/rest/worksheet/v1/5GSlice/choiceSnssai
    choiceSnssai() {
      let params = {
        wsnbr: this.wsnbr,
        WIRE: '1',
        TN: '0',
        CORE: '1'
      }
      choiceSnssai({ ...params }).then(data => {
        this.deploy()
      })
    },
    deploy() {
      const params = {
        wsnbr: [this.wsnbr],
        taskType: 'cfgdeploy',
        isSync: true,
        startTime: '',
        prilvl: '2',
        logLevel: 'Info',
        isCfgCheck: 'N',
        ignoreCfgErr: 'Y',
        netUserId: 'admin',
        sourceIP: '127.0.0.1'
      }
      //   api/biz/cfg/deploy
      deploy({ ...params }).then(data => {
        this.insertSnssaiByMdn()
      })
    },
    insertSnssaiByMdn() {
      const params = {
        userData: {
          MDN: this.formData.MDN,
          IMSI: this.infos.iMSI,
          mdnStatus: '0'
        },
        snssaiData: {
          wsnbr: this.infos.wsnbr,
          orderType: 'CREATE',
          snssai: this.infos.snssai,
          dnnName: this.infos.dnnName,
          dnnType: this.formData.dnnType,
          VDR: this.formData.VDR,
          expDataRateDL: this.formData.expDataRateDL,
          expDataRateUL: this.formData.expDataRateUL,
          usage: this.formData.usage === '专用切片+专用DNN' ? '1' : '2',
          stime: this.formData.stime,
          etime: this.formData.etime,
          maxNumberofPDUSession: this.formData.maxNumberofPDUSession
        }
      }
      //   api/rest/worksheet/v1/5GSlice/insertSnssaiByMdn
      insertSnssaiByMdn({ ...params }).then(data => {
        this.getServTask()
      })
    },
    getServTask() {
      let params = {
        wsnbr: this.wsnbr
      }
      // api/rest/worksheet/v1/5GSlice/getServTask
      getServTask(params).then(data => {
        let { taskid } = data
        this.taskid = taskid

        // 跳转到切片创建页面
        this.$router.push({
          path: '/slice/creating',
          query: {
            MDN: this.formData.MDN,
            wsnbr: this.wsnbr,
            taskid: this.taskid,
            insertParams: {
              userData: {
                MDN: this.formData.MDN,
                IMSI: this.infos.iMSI,
                mdnStatus: '1'
              },
              snssaiData: {
                wsnbr: this.infos.wsnbr,
                orderType: 'CREATE',
                snssai: this.infos.snssai,
                dnnName: this.infos.dnnName,
                dnnType: this.formData.dnnType,
                VDR: this.formData.VDR,
                expDataRateDL: this.formData.expDataRateDL,
                expDataRateUL: this.formData.expDataRateUL,
                usage: this.formData.usage === '专用切片+专用DNN' ? '1' : '2',
                stime: this.formData.stime,
                etime: this.formData.etime,
                maxNumberofPDUSession: this.formData.maxNumberofPDUSession
              }
            }
          }
        })
      })
    },
    getServTaskLogDetail() {
      let params = {
        wsnbr: this.wsnbr,
        taskid: this.taskid
      }
      // api/rest/worksheet/v1/5GSlice/getServTaskLogDetail
      getServTaskLogDetail(params).then(data => {
        let newSubTaskType = false
        let newExecstatus = true
        console.log('data', data)
        data.forEach((item, index) => {
          let { subTaskType } = item
          let { execstatus } = item

          if (subTaskType === 'sliceSign') {
            newSubTaskType = true

            if (+execstatus !== 0) {
              newExecstatus = false
            }
          }
        })

        if (newSubTaskType && newExecstatus) {
          if (this.taskid && this.taskid !== 'null') {
            // this.getSliceDataXXXXX()
            this.netWorkFlag()
            // this.translateFlag()
            this.coreFlag()
          }
        }
      })
    },
    deepClone(data) {
      return JSON.parse(JSON.stringify(data))
    },

    // 融合切片开通流程
    // 无线核心传输 流程进行
    //

    failureCase() {
      this.clearInterVal()

      Toast.clear()
      this.insertSnssaiByMdn2('0', this.failureReason)
    },
    clearInterVal() {
      if (this.RNID) {
        clearInterval(this.RNID)
        this.RNID = null
      }
      if (this.TNID) {
        clearInterval(this.TNID)
        this.TNID = null
      }
      if (this.CNID) {
        clearInterval(this.CNID)
        this.CNID = null
      }
    },
    successCase(type) {
      let obj = this.deepClone(this.domainIsSuccess)
      let flag = true
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          const element = obj[key]
          if (!element) {
            flag = element
          }
        }
      }

      if (flag) {
        this.clearInterVal()

        this.insertSnssaiByMdn2('1')
      }
    },
    netWorkFlag() {
      if (this.RNID) {
        clearInterval(this.RNID)
        this.RNID = null
      }
      this.RNID = setInterval(async () => {
        let data = await this.networkSliceCreate()
        console.log('data network', data)

        if (data === 'success') {
          clearInterval(this.RNID)
          this.RNID = null
          this.domainIsSuccess.RN = true
          this.successCase('RN')
        } else if (data === 'failure') {
          this.domainIsSuccess.RN = false
          this.failureCase()
        }
      }, 5000)
    },
    // 无线网子切片开通
    networkSliceCreate() {
      console.log('networkSliceCreate ~ 无线网子切片开通')
      let params = {
        taskid: this.taskid,
        wsnbr: this.wsnbr
      }
      // api/rest/worksheet/v1/5GSlice/getServTaskLogDetail
      return getServTaskLogDetail(params).then(async data => {
        if (data.length === 0) {
          return
        }
        let timeData = data.filter(item => {
          return item.subTaskType === 'rnResCreate'
        })

        if (timeData.length === 0) {
          return
        }

        console.log('timeData', timeData)
        if (
          timeData[timeData.length - 2] &&
          timeData[timeData.length - 2].execstatus &&
          timeData[timeData.length - 2].execstatus == 1
        ) {
          // this.domainIsSuccess.RN = false
          // this.failureCase()
          this.failureReason = timeData[timeData.length - 2].result
          return 'failure'
        }

        if (
          timeData[timeData.length - 1] &&
          timeData[timeData.length - 1].execstatus &&
          timeData[timeData.length - 1].execstatus == 0
        ) {
          return 'success'
        }
      })
    },

    translateFlag() {
      if (this.TNID) {
        clearInterval(this.TNID)
        this.TNID = null
      }
      this.TNID = setInterval(async () => {
        let data = await this.translateSliceCreate()
        console.log('🚀 ~ file: index.vue ~ line 1522 ~ this.TNID=setInterval ~ data', data)

        if (data === 'success') {
          clearInterval(this.TNID)
          this.TNID = null
          this.domainIsSuccess.TN = true
          this.successCase('TN')
        } else if (data === 'failure') {
          this.domainIsSuccess.TN = false
          this.failureCase()
        }
      }, 5000)
    },
    // 传输网子切片开通
    translateSliceCreate() {
      console.log('translateSliceCreate ~ 传输网子切片开通')
      let params = {
        taskId: this.taskid
      }
      // api/rest/worksheet/v1/5GSlice/getTnResCreateLog

      return getTnResCreateLog(params).then(data => {
        /*
            deployStatus 任务配置下发状态 processing：进行中
                                        success：成功
                                        failure：失败

            finishFlag 是否返回所有日志（包括成功和失败）Y：日志都已返回
                                                      N：日志未全部返回
          */

        if (!data) {
          return
        }
        let { deployStatus, finishFlag } = data

        if (finishFlag === 'Y') {
          return deployStatus
        }
      })
    },

    // 核心网循环调
    coreFlag() {
      if (this.CNID) {
        clearInterval(this.CNID)
        this.CNID = null
      }
      this.CNID = setInterval(async () => {
        let data = await this.coreSliceCreate()

        if (data === 'success') {
          // 成功 清除不继续判断 置状态
          clearInterval(this.CNID)
          this.CNID = null
          this.domainIsSuccess.CN = true
          this.successCase('CN')
        } else if (data === 'failure') {
          // 失败 停止流程 置状态
          this.domainIsSuccess.CN = false
          this.failureCase()
        }
      }, 5000)
    },

    // 核心网子切片开通
    coreSliceCreate() {
      console.log('coreSliceCreate ~ 核心网子切片开通')
      let params = {
        taskid: this.taskid,
        wsnbr: this.wsnbr
      }
      // return this.$utils
      //   .doRequest('api/rest/worksheet/v1/5GSlice/getServTaskLogDetail', { ...params }, 'get')
      return getServTaskLogDetail(params).then(async data => {
        if (data.length === 0) {
          return
        }

        let timeData = data.filter(item => {
          return item.subTaskType === 'cnResCreate'
        })

        if (timeData.length === 0) {
          return
        }

        let isFinish = false

        if (
          timeData[timeData.length - 1] &&
          timeData[timeData.length - 1].execstatus &&
          timeData[timeData.length - 1].execstatus == 1
        ) {
          // this.domainIsSuccess.CN = false
          // this.failureCase()
          this.failureReason = timeData[timeData.length - 1].result
          return 'failure'
        } else if (
          timeData[timeData.length - 1] &&
          timeData[timeData.length - 1].execstatus &&
          timeData[timeData.length - 1].execstatus == 0
        ) {
          isFinish = true
        }

        // this.coreSliceResult = arr

        let flag = await this.isFinishCore()

        if (flag) {
          if (isFinish) {
            // clearInterval(this.CNID)
            // this.CNID = null
            // this.domainIsSuccess.CN = true
            // this.successCase('CN')

            return 'success'
          }
        }
      })
    },

    async isFinishCore() {
      let params = {
        taskid: this.taskid,
        wsnbr: this.wsnbr
      }
      // let res = await this.$utils.doRequest('api/rest/worksheet/v1/5GSlice/getServTaskLogDetail', { ...params }, 'get')
      let data = await getServTaskLogDetail(params)

      if (data.length === 0) {
        return
      }

      let timeData = data.filter(item => {
        return item.subTaskType === 'Ping'
      })
      console.log('timeData', timeData)

      return timeData.length > 0
    },

    insertSnssaiByMdn2(failStatus, reason) {
      const params = {
        userData: {
          MDN: this.formData.MDN,
          IMSI: this.infos.iMSI,
          mdnStatus: '1'
        },
        snssaiData: {
          wsnbr: this.infos.wsnbr,
          orderType: 'CREATE',
          snssai: this.infos.snssai,
          dnnName: this.infos.dnnName,
          dnnType: this.formData.dnnType,
          VDR: this.formData.VDR,
          snssaiStatus: failStatus,
          failureCause: failStatus === '0' ? reason : '',
          expDataRateDL: this.formData.expDataRateDL,
          expDataRateUL: this.formData.expDataRateUL,
          usage: this.formData.usage === '专用切片+专用DNN' ? '1' : '2',
          stime: this.formData.stime,
          etime: this.formData.etime,
          maxNumberofPDUSession: this.formData.maxNumberofPDUSession
        }
      }

      // api/rest/worksheet/v1/5GSlice/insertSnssaiByMdn
      insertSnssaiByMdn(params).then(data => {
        this.$router.push({
          path: '/slice/create',
          query: { MDN: this.formData.MDN }
        })
      })
    },

    //
    onConfirmDNNType(val) {
      this.dnnTypeSelected = val
      this.showDNNPicker = false
    },
    onConfirmBusin(val) {
      this.formData.usage = val
      this.showBusinPicker = false
    },
    onConfirmTime(val) {
      // 对日期做判断
      if (this.checkTime(val, this.formData.etime)) {
        this.formData.stime = this.$moment(val).format('YYYY-MM-DD HH:mm:ss')
        this.showTimePicker = false
      }
    },
    onConfirmTimeEnd(val) {
      // 对日期做判断
      if (this.checkTime(this.formData.stime, val)) {
        this.formData.etime = this.$moment(val).format('YYYY-MM-DD HH:mm:ss')
        this.showTimePickerEnd = false
      }
    },
    // 校验开始时间和结束时间
    checkTime(sTime, eTime) {
      if (sTime && eTime) {
        if (this.$moment(sTime).isBefore(eTime)) {
          return true
        } else {
          Toast.fail('开始时间不能大于结束时间')
          return false
        }
      } else {
        return true
      }
    }
  },
  computed: {},
  created() {
  },
  mounted() {},
  destroyed() {}
}
</script>

<style lang='scss' scoped>
.sliceIssued {
}
</style>
